<template>
    <div class="mainView">
        <div class="leftView" :class="{ 'hidden': leftHidden }">
            <div class="flex-col">
                <div class="new-chat" @click="createNewChat">
                    <i class="fa-solid fa-magnifying-glass"></i>
                    <span class="new-chat-title">新搜索</span>
                    <i class="fa-solid fa-pen" style="padding-right: 5px;"></i>
                </div>
                <div v-for="(chatItem, index) in chatItems" :key="chatItem">
                    <div :key="index" :data-chat-id="index" class="chat-item" @click="toggleHidden(index)">
                        <div v-if="editingChatId === chatItem.chatId" class="chat-item-name">
                            <input v-model="chatItem.name" @blur="finishRenaming(chatItem.chatId, chatItem.name)"
                                @keydown.enter="finishRenaming(chatItem.chatId, chatItem.name)" class="renamechat" />
                        </div>
                        <div v-else class="chat-item-name">
                            {{ chatItem.seedKeyword }}
                        </div>
                        <transition name="fade">
                            <div class="chat-item-more" v-show="showMore && activeChatId === chatItem.chatId">
                                <i class="fa-solid fa-ellipsis" @click.stop="toggleOptions(chatItem.chatId)"></i>
                            </div>
                        </transition>
                    </div>
                </div>
            </div>
            <div class="user-card new-chat" @click="userSet">
                <i class="fa-regular fa-user fa-magnifying-glass" style="font-size: 25px;"></i>
                <span class="user-name new-chat-title">{{ this.userName }}</span>
                <div class="user-setting" v-if="isUserSetOpen" @click.stop>
                    <div class="setting-item">
                        <span class="user-name new-chat-title">{{ this.userName }}</span>
                    </div>
                    <div class="setting-item">
                        <span class="user-name new-chat-title">
                            <i class="fa-solid fa-location-dot" style="margin-right: 15px;"></i>
                            <span v-if="this.ifip === '0'">vip</span>
                            <span v-if="this.ifip === '1'">非VIP</span>
                        </span>
                    </div>
                    <div class="setting-item" @click="logout">
                        <span class="user-name new-chat-title">
                            <i class="fa-solid fa-arrow-right-from-bracket" style="margin-right: 5px;"></i>
                            注销
                        </span>
                    </div>
                </div>
            </div>
        </div>
        <div class="close-left" :class="{ 'hidden': leftHidden }" @click="closeLeft">
            <div v-if="leftHidden === false" class="tooltip">关闭侧栏</div>
            <div v-else class="tooltip">打开侧栏</div>
        </div>
        <transition name="fade">
            <div class="options-list" v-show="showOptions && activeChatId !== null">
                <ul>
                    <li @click="renamechat(this.activeChatId)">
                        <i class="fa-regular fa-pen-to-square"></i>
                        重命名
                    </li>
                    <li @click="dialogVisible = true" style="color: red;">
                        <i class="fa-regular fa-trash-can"></i>
                        删除
                    </li>
                </ul>
            </div>
        </transition>
        <div class="rightView">
            <div class="select_inputModel new-chat" @click="goToHome">
                <span>返回主页</span>
                <i class="fa-solid fa-backward" style="padding-left: 15px;"></i>
            </div>
            <div class="chat_part_con">
                <div class="chat_part" v-if="isNull === true">
                    <div style="height: 300px;margin-top:100px;width: 100%;">
                        <companimate />
                    </div>
                </div>
                <div class="chat_part" id="chat_part" v-else>
                    <el-card shadow="always">
                        <template #header>
                            <div class="card-header">
                                <span>关键词{{ this.keyword }}搜索中介关键词如下:</span>
                            </div>
                        </template>
                        <el-table :data="midData" border style="width: 100%">
                            <el-table-column label="序号" width="100px">
                                <template #default="scope">{{ scope.$index + 1 }}</template>
                            </el-table-column>
                            <el-table-column prop="recommendName" label="中介词" />
                            <el-table-column prop="thumpUp" sortable label="点赞" />
                            <el-table-column prop="thumbDown" sortable label="点踩" />
                            <el-table-column prop="commentNum" sortable label="评论" />
                            <el-table-column label="操作" width="200px">
                                <template #default="scope">
                                    <div style="display: flex;">
                                        <el-radio-group v-model="scope.row.op">
                                            <el-radio-button label="点赞" value="1" size="small" @click="sendlike(scope.row.recommendName,0)"/>
                                            <el-radio-button label="点踩" value="2" fill="#ffcccc" size="small"@click="sendlike(scope.row.recommendName,1)" />
                                        </el-radio-group>
                                        <el-button size="small" type="primary" style="margin-left: 10px;"
                                            @click="handlecomments(scope.row.recommendName, scope.row.recommendId)">
                                            评论
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                    <div style="height: 50px;"></div>
                    <el-card shadow="always">
                        <template #header>
                            <div class="card-header">
                                <span>关键词{{ this.keyword }}搜索推荐竞争词如下:</span>
                            </div>
                        </template>
                        <el-table :data="compData" border style="width: 100%">
                            <el-table-column label="序号" width="100px">
                                <template #default="scope">{{ scope.$index + 1 }}</template>
                            </el-table-column>
                            <el-table-column prop="recommendName" label="竞争词" />
                            <el-table-column prop="competitiveness" sortable label="竞争度" />
                            <el-table-column prop="thumbUp" sortable label="点赞" />
                            <el-table-column prop="thumbDown" sortable label="点踩" />
                            <el-table-column prop="commentNum" sortable label="评论" />
                            <el-table-column label="操作" width="200px">
                                <template #default="scope">
                                    <div style="display: flex;">
                                        <el-radio-group v-model="scope.row.op">
                                            <el-radio-button label="点赞" value="1" size="small"@click="sendlike(scope.row.recommendName,0)" />
                                            <el-radio-button label="点踩" value="2" fill="#ffcccc" size="small"@click="sendlike(scope.row.recommendName,1)" />
                                        </el-radio-group>
                                        <el-button size="small" type="primary" style="margin-left: 10px;"
                                            @click="handlecomments(scope.row.recommendName, scope.row.recommendId)">
                                            评论
                                        </el-button>
                                    </div>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-card>
                    <div style="height: 50px;"></div>
                </div>
            </div>
            <div class="question">
                <div class="contain_chat">
                    <textarea ref="textareaRef" v-model="content" class="chat_input" :rows="rows"
                        placeholder="请输入种子关键词"></textarea>
                    <div class="sendQuestion" @click="sendQuestionBtn">
                        <i :class="['fa-regular', 'fa-circle-up', isContentEmpty ? 'disabled' : 'enabled']"
                            style="font-size: 30px;"></i>
                    </div>
                </div>
            </div>
            <div style="width: 100%;justify-content: center;">
                <div style="color: #d0d0d0;margin: 10px auto;width:280px">以上推荐仅供参考，请检查重要信息。</div>
            </div>
        </div>
    </div>
    <el-dialog v-model="dialogVisible" title="警告" width="500" :before-close="handleClose"
        style="border-radius: 15px;background-color: #212121;">
        <span style="color: #a0a0a0;">您确定要删除此搜索吗？请注意此操作不可逆！</span>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="deleteChat()" style="background-color: red;border:none;">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
    <el-dialog v-model="commentsdialogVisible" :title="commentword+'评论'" width="700" :before-close="handleClose"
        style="border-radius: 15px;background-color: #212121;">
        <el-table :data="commentsData" style="width: 100%" :show-header="false">
            <el-table-column width="80px">
                <el-avatar :size="50" :src="circleUrl" />
            </el-table-column>
            <el-table-column label="评论">
                <template #default="scope">
                    <div style="display: flex;flex-direction: column">
                        <div style="line-height: 50px;">{{ scope.row.username }}</div>
                        <div>{{ scope.row.commentContent }}</div>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <div style="margin-top: 10px;">
                <el-input v-model="input" style="width: 100%" placeholder="输入评论" clearable />
                <el-button type="primary"  style="border:none;margin-top: 10px;" @click="sendcomment">
                    发送
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>
<script>
import $ from 'jquery'
import { ref, watch, nextTick, onMounted } from 'vue'
import axios from 'axios'
import companimate from "./companimate.vue"

export default {
    name: 'Main',
    components: {
        companimate,
    },
    data() {
        return {
            keyword: "",
            commentword: "",
            chatItems: [],
            userId: localStorage.getItem("userId"),
            input: "",
            compData: [],
            commentsData: [],
            midData: [],
            showMore: false,
            showOptions: false,
            leftHidden: false,
            activeChatId: null,
            isNull: true,
            isUserSetOpen: false,
            content: '',
            userName: localStorage.getItem('username'),
            editingChatId: null,
            dialogVisible: false,
            commentsdialogVisible: false,
        };
    },
    computed: {
        isChatItemActive() {
            return (chatId) => {
                return this.showMore && this.activeChatId === chatId;
            };
        },
        isContentEmpty() {
            return this.content.trim() === '';
        },
    },
    methods: {
        logout() {
            this.userName = "用户名";
            this.$router.push('/');
        },
        goToHome() {
            this.$router.push({ name: 'Home' })
        },
        async sendlike(name , type){
            try {
                const response = await axios({
                    url: `http://127.0.0.1:8090/api/keyword/isLike`,
                    method: 'POST',
                    params:{
                        recommendName:name,
                        seedKeyword:this.keyword,
                        isLike:type,
                        userId:this.userId
                    }
                });
                console.log('改对话标题发送到后端:', response.data);
            } catch (error) {
                console.error('改对话标题到后端时出错:', error);
            }
        },
        async handlecomments(a, b) {
            this.commentword = a;
            const response = await axios({
                url: `http://127.0.0.1:8090/api/keyword/comment`,
                method: 'GET',
                params: {
                    recommendId:b
                }
            })
            this.commentsData = response.data
            this.commentsdialogVisible = true;
        },
        async fetchChatItemsByAjax() {
            const response = await axios({
                url: `http://127.0.0.1:8090/api/search/user`,
                method: 'GET',
                params: {
                    userId: this.userId
                }
            })
            return response
        },
        async fetchChatItems() {
            const [err, result] = await this.promise_error_process(this.fetchChatItemsByAjax())
            if (err) {
                console.log("获取列表失败")
            } else {
                console.log(result.data)
                this.chatItems = result.data
            }
        },
        async deleteChat() {
            this.dialogVisible = false;
            for (var i = 0; i < this.chatItems.length; i++)
                if (this.chatItems[i].chatId === this.activeChatId) {
                    this.chatItems.splice(i, 1);
                    break;
                }
            try {
                const response = await axios({
                    url: `http://127.0.0.1:8080/api/chat/${this.activeChatId}`,
                    method: 'DELETE',
                });
                console.log('删除chatid发送到后端:', response.data);
            } catch (error) {
                console.error('删除chatid到后端时出错:', error);
            }
            this.activeChatId = null;
        },
        renamechat(chatId) {
            this.editingChatId = chatId;
            this.closeOptions();
            this.$nextTick(() => {
                const inputs = $('.renamechat');
                inputs.focus();
                inputs.setSelectionRange(inputs.value.length, inputs.value.length);
            });
        },
        async finishRenaming(chatId, newName) {
            this.editingChatId = null;
            console.log(chatId, newName)
            try {
                const response = await axios({
                    url: `http://127.0.0.1:8080/api/chat/${this.activeChatId}/name`,
                    method: 'POST',
                    data: { name: newName }
                });
                console.log('改对话标题发送到后端:', response.data);
            } catch (error) {
                console.error('改对话标题到后端时出错:', error);
            }
        },
        userSet() {
            this.isUserSetOpen = !this.isUserSetOpen;
        },
        closeLeft() {
            this.leftHidden = !this.leftHidden;
        },
        toggleHidden(chatId) {
            if (this.activeChatId !== chatId) {
                this.activeChatId = chatId;
                console.log(this.activeChatId);
                this.showMore = true;
                $('.chat-item').removeClass('bg-changed');
                $('.chat-item-more').hide();
                $('.chat-item-name').removeClass('hidden');
                $('.chat-item[data-chat-id="' + this.activeChatId + '"]').addClass('bg-changed').find('.chat-item-more').show();
                const activeElement = $('.chat-item[data-chat-id="' + this.activeChatId + '"]');
                activeElement.find('.chat-item-name').addClass('hidden');
                this.updateOptionsListPosition(activeElement);
                this.isNull = false;
                this.fetchChatItemInfo(chatId);
            }
        },
        updateOptionsListPosition(element) {
            const $element = $(element);
            const offset = $element.offset();
            const optionsList = $('.options-list');
            optionsList.css({
                top: offset.top
            })
        },
        toggleOptions(chatId) {
            this.showOptions = !this.showOptions;
            this.activeChatId = chatId;
        },
        closeOptions() {
            this.showOptions = false;
        },
        closeOptionsOutside(event) {
            if (!event.target.closest('.options-list')) {
                this.closeOptions();
            }
        },
        createNewChat() {
            this.midData = [];
            this.compData = [];
            this.activeChatId = null;
            this.showMore = false;
            $('.chat-item').removeClass('bg-changed');
            this.isNull = true;
            console.log(this.message);
        },
        scrollToBottom() {
            this.$nextTick(() => {
                var scrollHeight = $('#chat_part').prop("scrollHeight");
                $('#chat_part').animate({ scrollTop: scrollHeight }, 500);
            })
        },
        //使用结构赋值进行异常处理
        promise_error_process(promise) {
            return promise.then(data => [null, data])
                .catch(err => [err, null])
        },
        fetchChatItemInfo(index) {
            this.midData = this.chatItems[index].intermediaryList
            this.midData = this.chatItems[index].recommendList
            this.keyword = this.chatItems[index].seedKeyword
        },
        async sendQuestionByAjax(que){
            const response = await axios({
                url:        `http://127.0.0.1:8090/api/search/competition`,
                method:     'GET',
                params:{
                    seedKeyword: que,
                    searchUserId : this.userId
                }
            })
            return response
        },
        async sendQuestion(que) {
            const [err, result] = await this.promise_error_process(this.sendQuestionByAjax(que))
            if (err) {
                console.log("发送问题失败")
            } else {
               this.midData=result.data.intermediaryList;
               this.compData=result.data.recommendList ;
               this.fetchChatItems();
            }
        },
        sendQuestionBtn() {
            if (this.content === '') return;
            console.log(this.isNull);
            this.isNull = false;
            this.sendQuestion(this.content);
            this.content = '';
        },
        async sendcommentByAjax(){
            const response = await axios({
                url:        `http://127.0.0.1:8090/api/keyword/comment`,
                method:     'PUT',
                params:{
                    seedKeyword: this.keyword,
                    recommendName : this.commentword,
                    comment:this.input,
                    userId:this.userId,
                }
            })
            return response
        },
        async sendcomment(){
            if(this.input === "") return ;
            const [err, result] = await this.promise_error_process(this.sendQuestionByAjax(que))
            if (err) {
                console.log("发送问题失败")
            } else {
                this.commentsData.push({
                    username:this.userName,
                    commentContent:this.input,
                });
                this.input = "";
            }
        }
    },
    mounted() {
        this.fetchChatItems();
        document.addEventListener('click', this.closeOptionsOutside);
        $('.flex-col').on('scroll', () => {
            if (this.activeChatId) {
                const activeElement = $('.chat-item[data-chat-id="' + this.activeChatId + '"]');
                this.updateOptionsListPosition(activeElement);
            }
        });

    },
    created() {
    },
    setup(props, { emit }) {
        const textareaRef = ref(null);
        const rows = ref(1)
        const content = ref('')

        onMounted(() => {
            nextTick(adjustTextareaSize);
        });

        watch(() => content.value, () => {
            nextTick(adjustTextareaSize);
        })

        // 参考vant组件库中的field组件
        const adjustTextareaSize = () => {
            let textarea = textareaRef.value

            textarea.style.height = 'auto';
            const height = textarea.scrollHeight;

            if (height) { // 改变textarea高度达到自适应
                textarea.style.height = height + "px";
            }
        }
        return {
            textareaRef,
            rows,
            content
        }
    }
}
</script>
<style>
.el-dialog__title {
    color: #b0b0b0;
}
</style>
<style scoped>
.mainView {
    position: relative;
    display: flex;
    height: 100%;
    overflow: hidden;
    background-color: #252525;
}

.close-left {
    position: absolute;
    z-index: 100;
    left: 265px;
    top: 50%;
    height: 40px;
    width: 8px;
    background-color: #a0a0a0;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 1s ease-in-out, background-color 0.3s ease-in-out;
}

.close-left.hidden {
    transform: translateX(-255px);
}

.close-left:hover {
    background-color: white;
}

.close-left .tooltip {
    visibility: hidden;
    width: 80px;
    background-color: #171717;
    color: #fff;
    text-align: center;
    border-radius: 10px;
    padding: 5px 0;
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
    white-space: nowrap;
}

.close-left:hover .tooltip {
    visibility: visible;
    opacity: 1;
}

.leftView {
    display: flex;
    flex-direction: column;
    width: 250px;
    background-color: #171717;
    padding: 12px;
    padding-right: 5px;
    transition: transform 1s ease-in-out, width 1s ease-in-out;
}

.leftView.hidden {
    transform: translateX(-274px);
    width: 0px;
    margin: 12px 0;
}

.flex-col {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    max-height: 100%;
    max-width: 250px;
    overflow-y: auto;
    overflow-x: visible;
}

::-webkit-scrollbar {
    visibility: hidden;
    width: 5px;
    background-color: black;
}

::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
    background-color: #555;
}

.time-tag {
    padding: 10px;
    font-size: 15px;
    margin-top: 10px;
    color: #ccc;
}

.new-chat {
    padding: 5px;
    height: 40px;
    display: flex;
    align-items: center;
    border-radius: 10px;
}

.new-chat:hover {
    background-color: #212121;
    cursor: pointer;
    transition: 0.3s;
}

.fa-magnifying-glass {
    font-size: 20px;
    padding-left: 8px;
}

.new-chat-title {
    flex: 1;
    padding-left: 10px;
}

.chat-item {
    padding: 10px;
    margin: 3px 0;
    height: 35px;
    display: flex;
    align-items: center;
    border-radius: 10px;
    position: relative;
}

.chat-item.bg-changed {
    background-color: #212121;
}

.chat-item:hover {
    background-color: #212121;
    cursor: pointer;
    transition: 0.3s;
}

.renamechat {
    background-color: transparent;
    outline: none;
    border: none;
    color: white;
    font-size: 15px;
}

.chat-item-name {
    background-color: transparent;
    color: white;
    outline: none;
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    mask-image: linear-gradient(to right, black 80%, transparent 100%);
    -webkit-mask-image: linear-gradient(to right, black 80%, transparent 100%);
}

.chat-item-name.hidden {
    mask-image: linear-gradient(to right, black calc(100% - 60px), transparent 90%);
    -webkit-mask-image: linear-gradient(to right, black calc(100% - 60px), transparent 90%);
}

.chat-item-more {
    z-index: 10;
    right: 10px;
    top: 0;
    bottom: 0;
    position: absolute;
    width: 60px;
    display: flex;
    flex-direction: row-reverse;
    align-items: center;
}

.chat-item-more.show {
    visibility: hidden;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
}

.options-list {
    position: absolute;
    left: 250px;
    top: 0;
    background-color: #2f2f2f;
    border: 1px solid #444444;
    border-radius: 10px;
    padding: 8px;
    z-index: 1000;
}

.options-list ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

.options-list li {
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 8px;
}

.options-list li:hover {
    background-color: #424242;
}

.user-card {
    margin-top: 10px;
    position: relative;
}

.user-setting {
    position: absolute;
    top: -150px;
    left: 0 px;
    width: 220px;
    height: 140px;
    background-color: #201e1e;
    border: 1px solid #464242;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 10px;
}

.setting-item {
    font-size: 18px;
    margin-top: 10px;
    border-bottom: #555 1px solid;
    padding-bottom: 10px;
    padding-left: 10px;
}

.setting-item:first-child {
    margin-top: 0;
}

.setting-item:last-child {
    border-bottom: 0px;
    padding-bottom: 0;
}

.rightView {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    flex: 1;
    background-color: #252525;
}

.select_inputModel {
    width: 135px;
    height: 55px;
    margin-top: 10px;
    text-align: center;
    position: relative;
    font-size: 18px;
    padding-left: 15px;
}

.selectView {
    position: absolute;
    bottom: -105px;
    left: -2px;
    width: 173px;
    height: 100px;
    background-color: #201e1e;
    border: 1px solid #464242;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.option_model {
    width: 150px;
    margin: 10px;
    padding: 5px 0;
    border-radius: 8px;
}

.option_model:hover {
    background-color: gray;
}

.option_name {
    margin-left: 10px;
}

.null {
    text-align: center;
    margin-top: 150px;

}

.chat_part {
    overflow-y: auto;
    font-size: 18px;
    width: 70%;
    height: 100%;

}

.chat_part::-webkit-scrollbar {
    display: none;
}

.chat_part_con {
    padding-top: 30px;
    display: flex;
    justify-content: center;
    width: 100%;
    flex: 1;
    overflow-y: auto;
}

.ai_tool {
    text-align: left;
    margin-top: 30px;
    margin-left: 50px;
    display: flex;
}

.ai_head {
    border-radius: 50%;
    width: 40px;
    height: 40px;
}

.icon_ai {
    margin-right: 20px;
    margin-top: 10px;
}

.icon_user {
    margin-left: 20px;
}

.user {
    text-align: right;
    display: flex;
    justify-content: flex-end;
    margin-top: 30px;
    margin-right: 50px;
}

.user_head {
    border-radius: 50%;
    width: 40px;
    height: 40px;
}

.msg_content {
    white-space: pre-line;
    max-width: 600px;
    word-wrap: break-word;
    margin-top: 8px;
}

.identify {
    font-size: 12px;
}

.question {
    display: flex;
    width: 100%;
    color: #fff;
    align-items: center;
    justify-content: center;
}

.contain_chat {
    display: flex;
    margin: 0 auto;
    width: 60%;
    min-height: 50px;
    max-height: 215px;
    border-radius: 30px;
    background-color: #2f2f2f;
    padding: 5px;
    padding-left: 15px;
}

.chat_input {
    flex: 1;
    min-height: 20px;
    max-height: 200px;
    resize: none;
    font-size: 18px;
    border-radius: 18px;
    border: 0;
    outline: none;
    background-color: transparent;
    color: #ccc;
    padding: 10px;
    margin-right: 10px;
}

.sendQuestion {
    display: flex;
    flex-direction: column-reverse;
    padding-right: 5px;
    padding-bottom: 5px;
}

.sendQuestion i.enabled {
    color: #fff;
}

.sendQuestion i.disabled {
    color: #a0a0a0;
}

.sendQuestion i:hover {
    color: #d0d0d0;
}
</style>